package com.lingjtx.oss.controller;

import com.lingjtx.common.core.ResponseResult;
import com.lingjtx.common.core.model.api.OssUploadResponseItem;
import com.lingjtx.oss.common.ReactiveOSSService;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 公有云OSS存储
 */
@RestController
@RequestMapping("/pub")
public class PubOSSController {

    private final ReactiveOSSService reactiveOSSService;

    public PubOSSController(ReactiveOSSService reactiveOSSService) {
        this.reactiveOSSService = reactiveOSSService;
    }

    /**
     * 单文件上传
     */
    @PostMapping("/upload/single")
    public Mono<ResponseResult<OssUploadResponseItem>> singleUpload(@RequestPart("file") Mono<FilePart> filePartMono,
                                                                    @RequestParam(value = "folderType", defaultValue = "0") Integer folderType) {
        return filePartMono
                .flatMap(filePart -> reactiveOSSService.upload(folderType, filePart))
                .map(ResponseResult::createBySuccess)
                .onErrorResume(e -> Mono.just(ResponseResult.createByError("上传失败: " + e.getMessage())));
    }

    /**
     * 多文件上传
     */
    @PostMapping("/upload/multi")
    public Mono<ResponseResult<List<OssUploadResponseItem>>> multiUpload(@RequestPart("files") Flux<FilePart> fileParts,
                                                                         @RequestParam(value = "folderType", defaultValue = "0") Integer folderType) {
        return fileParts
                .flatMap(filePart -> reactiveOSSService.upload(folderType, filePart))
                .collectList()
                .map(ResponseResult::createBySuccess)
                .onErrorResume(e -> Mono.just(ResponseResult.createByError("上传失败: " + e.getMessage())));
    }
}
